import { createStore } from 'vuex'
import api from '@/plugins/api/index'
import router from "@/router";

export default createStore({
  state: {
    userInfo: {},
    routerHistory: [],
    nowRouterName: ''
  },
  getters: {
  },
  mutations: {
    // 登录成功保存用户信息
    updateUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    updateRouterHistory(state, router) {
      const aIndex = state.routerHistory.findIndex(item => item.name === router.name)
      if (aIndex === -1) {
        state.routerHistory.push(router)
      }
      state.nowRouterName = router.name
    },
    delRouterHistory(state, index) {
      let routerData = {}
      let routerName = state.routerHistory[index].name
      if (routerName === state.nowRouterName) {
        if (state.routerHistory.length === 1) {
          routerData = {
            path: '/',
            name: 'index',
            meta: {
              title: '首页'
            },
          }
        }else if (index === 0) {
          routerData = state.routerHistory[index + 1]
        } else {
          routerData = state.routerHistory[index - 1]
        }
        state.nowRouterName = routerData.name
        router.push(routerData.path)
      }
      state.routerHistory.splice(index, 1)

    },
    // 退出登录
    async outLogin(state) {
      const res = await api.outLogin({
        userId: state.userInfo.id
      })
      if (res.data.code === 200) {
        state.userInfo = {}
        window.sessionStorage.clear()
        window.location.replace('/login')
      }

    },
    async getUserInfo(state) {
      return
      const res = await api.getUserInfo()
      if (res.data.code === 200) {
        state.userInfo = res.data.data.userInfo
      }
    }
  },
  actions: {
  },
  modules: {
  }
})
